<template>
	<div v-if="data.length > 0">
		<div class="treeRadio" v-for="(item, index) in treeData" :key="index">
			<div class="item" >
				<div class="left">
					
          <div class="expanded iconfont icon-sanjiaoxing" :class="{down: item.scopesDefault}" v-show="item.children"
            @click.stop="showlist(index)">
          </div>

          <!-- !props.checkStrictly -->
          <div v-if="!props.checkStrictly ">
            <div class="checkbox"
            v-if="item.children"
            :class="{'select': item.selectAll}"
            @click="selectChange(index, item)"
            >
              <!-- 全选 -->
              <i :class="`iconfont icon-duigou ${item.selectAll}`" v-show="item.selectAll == 2"></i>

              <!-- 至少选了一个 但没有全选 -->
              <i class="iconfont" v-show="item.selectAll == 1">-</i>
            </div>

            <div class="checkbox"
            v-else
            :class="{'select': item.checked}"
            @click="selectChange(index, item)"
            :style="{marginLeft: '20px'}">
              <i class="iconfont icon-duigou" v-show="item.checked"></i>
            </div>
          </div>

          <div v-else>
            <div class="checkbox"
            
            :class="{'select': item.checked}"
            @click="selectChange(index, item)"
            :style="{marginLeft: item.children ? '0' : '20px'}">
              <i class="iconfont icon-duigou" v-show="item.checked"></i>
            </div>
          </div>

          <div @click="selectChange(index, item)">{{item[props.label]}}</div>
				</div>
			

			</div><!-- item.scopesDefault ? item.height + 'px' : 0 -->
			<div v-if="item.children && item.children.length > 0"
        :style="{...item.styles, transition: accordion ? 'all 0.4s' : ''}"
        :class="`tree_children children_${item.id}`">
        
				<tree
        :ref="`children_${item.id}`"
        @selectChangeData="selectChangeData"
        @setStyles="setStyles"
        :data="item.children" :props="props"
        :defaultCheckedKeys="defaultCheckedKeys"></tree>
			</div>

		</div>
	</div>

</template>

<script>
	export default {
		name: 'tree',
		// comments: {
		// 	treeMenus
		// },
		props: {
			data: {
				type: Array,
				default: () => {
					return []
				},
			},
      props: {
        type: Object,
        default: () => {
          return {
            value: 'id',
            label: 'category_name',
            // label: 'dictValue',
            // parentId: 'parentId',
            multiple: true, // 是否多选 默认true
            checkStrictly: false   //选择任意一级选项 默认false
          }
        }
      },
			// 手风琴效果
			accordion: {
				type: Boolean,
				default: true
			},
			// 选中的集合
      defaultCheckedKeys: {
        type: Array,
				default: () => {
          return []
          // return [['2023021', '2023023', '2023024', '2024021', '2025020'], ['2023021', '2023023', '2023024', '2024023']]
					// return ['2023021,2023023,2023024,2024021,2025020', '2023021,2023023,2023024,2024023']
				}
      }
			
		},
		data() {
			return {
				treeData: [],
        checkedData: [],
				selectData: [],// 选中的数据
				open: false,
        checkStrictly: false,
				// elClass: this.$u.guid(),
			}
		},

		watch: {
      defaultCheckedKeys() {
        // console.log(111111)
        // this.treeData = JSON.parse(JSON.stringify(this.data))
        // this.setTreeStyle()
      }
			// selectData(newArr) {
			// 	// console.log('selectChange', newArr)
			// 	this.$emit('selectChangeData', newArr)
			// }
		},
		created() {
      // console.log(this.defaultCheckedKeys)
			this.treeData = JSON.parse(JSON.stringify(this.data))
      // this.checkStrictly = this.props.
			this.setTreeStyle()
			// this.getTreeIdList()
		},
		methods: {
			setTreeStyle() {
        
				const treeFun = (arr, level = 0, parentId = false) => {
          level++
					arr.map((item, index) => {
						
            item.level = level
            if (parentId) {
              item['$parentId'] = parentId
            }
            
            item.styles = {
							height: '0',
						}
            item.scopesDefault = false
            // item.checked = true
            // item.selectAll = 2
            this.defaultCheckedKeys.forEach(ele => {
              ele.forEach((x, y) => {
                if (item.id === x) {
                  item.scopesDefault = true 
                  //console.log(1111, x, item[this.props.label], index)
                  // item.styles = {
                  //   height: 'auto',
                  // }
                  
                  if (y === ele.length - 1) {
                    item.checked = true
                    // item.selectAll = 2
                    // this.$forceUpdate()
                    // this.selectChange(index)
                  }
                  
                  
                }
                
              })
              
            })

						this.$forceUpdate()
						if (item?.children) {
              // item.selectAll = 0
              this.selectChangeData({row: this.treeData, flag: true})
              this.setStyles(item.children)
							treeFun(item.children, level, item.id)

						}
					})
				}
				treeFun(this.treeData)
				// this.setStyles()
				//console.log(this.treeData)
			},
      // 获取父级id路径 parentIdWay
			getTreeIdList(parentId) {
				let idaArr = []
				const getTreeIdList = (arr, id) => {
					arr.map((item, index) => {
						
						if (id === item.id) {
							idaArr.unshift(item.id)
							// console.log(idaArr, this.treeData)
						
							getTreeIdList(this.treeData, item['$parentId'])
							
						}
						if (item?.children) {
							getTreeIdList(item.children, id)
						}
						
					})
				
				}
				getTreeIdList(this.treeData, parentId)
				// console.log(idaArr)
        return idaArr
			},
			setStyles(e) {
				
				if (e) {
					const setTree = (arr) => {
						arr.map((item, index) => {
							if (e[0]['$parentId'] == item.id) {
								item.children = e
							}
							if (item?.children) {
								setTree(item.children)
							} 
							
						})
					}
					setTree(this.treeData)
				}
				
				const treeFun = (arr) => {
					arr.map((item, index) => {

						if (item?.children) {
							this.getTreeHeight(item.children, 36).then(res => {
                // console.log(res)
								if (item.scopesDefault) {
									item.styles = {
										height: res + 'px',
										
									}

									this.$forceUpdate()
								} else {
									item.styles = {
										height: 0,
										
									}
									this.$forceUpdate()
									
								}
							})
							treeFun(item.children)

						}
					})

				}
				treeFun(this.treeData)
				
				this.$emit('setStyles', this.treeData)
				// console.log(this.treeData)
			},
      setChecked(checked) {
        console.log(111111, this.treeData)
        const setChecked = (arr) => {
          arr.map(item => {
            item.checked =  checked
            if (this.$refs[`children_${item.id}`]) {
              // console.log(this.$refs[`children_${item.id}`])
              this.$refs[`children_${item.id}`][0].setChecked(checked)
            }
           
            if (item?.children) {
              // console.log(item)
              item.selectAll = checked ? 2 : 0
              setChecked(item.children)
            }
            this.$forceUpdate()
          })
        }
        setChecked(this.treeData)
        //console.log(this.treeData)
        // this.$forceUpdate()
      },
      // 选择所有子级
      selectParent(id, checked) {
        this.treeData.forEach(item => {
          
          if (item.id === id) {
            console.log(this.$refs[`children_${item.id}`][0], item.selectAll)
            item.selectAll =  item.selectAll === 2 ? 0 : (item.selectAll === 0 || item.selectAll === 1) ? 2 : checked ? 2 : 0
            console.log( item.selectAll)
            this.$refs[`children_${item.id}`][0].setChecked(item.selectAll === 2 ? true : false)
            this.$forceUpdate()
          }

        })
        console.log(this.treeData)
      },
			// 选中
			selectChange(index) {
        // console.log(this.treeData[index], this.props.multiple)
				this.treeData[index].checked = !this.treeData[index].checked
				// 选中的数据
        // this.props.multiple
        if (this.treeData[index]?.children && !this.props.checkStrictly) {
          // this.treeData[index].selectAll = this.treeData[index].checked ? 2 : 0
          // 选择有下级的
         
          this.selectParent(this.treeData[index].id, this.treeData[index].checked)
         

          const setChecked = (arr) => {
            arr.map(item => {
              item.checked = this.treeData[index].checked
             
              if (item?.children) {
                // item.selectAll = this.treeData[index].checked ? 2 : 0
                setChecked(item.children)
              }
            })
          }
          setChecked(this.treeData[index].children)
          // console.log(11111, this.treeData[index].children)
          this.selectChangeData({row: this.treeData[index].children})
          // this.$emit('selectChangeData',  arr)
        } else {
          this.checkedData = []
          this.checkedData.push(this.treeData[index])
          
          // console.log(this.checkedData)
          this.selectChangeData({row: this.checkedData})
          // this.$emit('selectChangeData', this.checkedData)
        }
				//this.$emit('selectChangeData', )
				
				this.$forceUpdate()
				// console.log()
			},
      
      judgeFun(e) {
        // console.log(e)
        const setCheckedTree = (arr, id, checked) => {
          arr.map((item) => {
            if (id === item.id) {
              item.checked = checked
            }
            if (item?.children) {
              // item.selectAll = checked ? 2 : 0
              setCheckedTree(item.children, id, checked)
            } 
            
          })
        }
        
        e.forEach(item => {
          setCheckedTree(this.treeData, item.id, item.checked)
        })
        // setTree(this.treeData)


        const getSelectAll = (arr) => {
          // let selectAll = 0// 0/一个都没选 1/最少选了一个 2/全选
          let selectArr = []
          arr.forEach(item => {
            
            if (item?.children) {
              let selectAll = 0
              if (item.selectAll === 0) {
                selectArr.push(false)
               
              } else if(item.selectAll === 2) {
                selectArr.push(true)
               
              } else {
                getSelectAll(item.children).forEach((ele, i) => {
                  if (ele == 0) {
                    return
                  }
                  if (ele) {
                    selectAll += 1
                  } else {
                    // console.log(111, item.children[i].selectAll)
                    if (item.children[i].selectAll == 2) selectAll += 1
                  
                  }
                  if (item.children[i].selectAll == 1) selectAll -= 1
                })
                // console.log('selectAll', item[this.props.label], selectAll, item.children)
                // selectArr.push(selectAll)
                selectArr.push(selectAll == item.children.length ? true : selectAll)
                // console.log('selectAll', item[this.props.label], selectAll, item.children.length, item.children)
                
                getSelectAll(item.children)
              }
              
              
            } else {
              if (!item.checked) {
                //selectAll = false
                selectArr.push(false)
              } else {
                selectArr.push(true)
              }
            }
          })

          // console.log('22selectArr', arr, selectArr)
          return selectArr
          //return Promise.resolve(selectArr)
        }
        
        const judgeFun = (arr) => {
          arr.forEach(item => {

            if (item?.children) {
              
              
              let flag = false
              let num = 0
              let selectAll = 0
              let selectArr = getSelectAll(item.children)
            
              selectArr.forEach((ele, i) => {
                if (!isNaN(ele) && ele !== true && ele > 0) {
                  flag = true
                }
                if (ele === 0) {
                 //console.log(33333333, ele)
                  if (selectArr.length > 1) {
                    num++
                  } 
                  return
                  
                  
                }
                if (ele) {
                  selectAll += 1
                } else {
                  
                  if (item.children[i].selectAll == 2) selectAll += 1
                }
                if (item.children[i].selectAll == 1) selectAll -= 1
              })

              //  0/一个都没选 1/最少选了一个 2/全选
              item.selectAll = flag ? 1 : selectAll === selectArr.length ? 2 : selectAll > 0 ? 1 : num > 0 ? 1 :0 
              // console.log(2222, item[this.props.label], item.selectAll, item.children , selectArr)
              this.$forceUpdate()
              judgeFun(item.children)
               
              
            }
          })
          
        }
        
        judgeFun(this.treeData)
        //this.$forceUpdate()
        // console.log(this.treeData)
      },
      noRepeat(arr) {
        for(var i = 0; i < arr.length - 1; i++){
            for(var j = i+1; j < arr.length; j++){
                if(arr[i].id === arr[j].id){
                    arr.splice(j,1);
                    
                    j--;
                }
            }
        }
        return arr;
      },
      // 单选
      radioFun(id) {
        const radioFun = (arr) => {
          arr.forEach(item => {
            if (item.id !== id) {
              item.checked = false
            }
            this.$forceUpdate()
            if (item?.children) {
              if (this.$refs[`children_${item.id}`] && item.id !== id) {
                //console.log(this.$refs[`children_${item.id}`], `children_${item[this.props.label]}`)
                this.$refs[`children_${item.id}`][0].setChecked(false, id)
              }
              
              radioFun(item.children)
            }
          })
        }
        radioFun(this.treeData)
        console.log('单选', this.treeData)
      },
			selectChangeData(e) {
        
        let selectData = []

        if (!this.props.multiple) {
          // 单选
          this.selectData = []
          this.radioFun(e.row[0].id)
        }
        //this.selectData = []
        const getChecked = (arr) => {
          arr.forEach(item => {
            // !item?.children || this.props.checkStrictly || !this.props.multiple
            if (!item?.children || this.props.checkStrictly) {
              this.selectData.unshift(item)
            }
            
            if (item?.children) {
              //item.selectAll = item.checked ? 2 : 0
              getChecked(item.children)
            }
          })
        }
        getChecked(e.row)
        
        selectData = this.selectData.filter(item => {
          if (item.checked) {
            return item
          }
        })
        
        selectData = this.noRepeat(selectData)
        // this.selectData.forEach((item, index) => {
        //   if (item.checked) {
        //     selectData.push(item)
        //   }
        // })

        if (this.treeData[0].level=== 1 && !e.flag) {
          
          selectData.map(item => {
            item.parentIdWay = [...this.getTreeIdList(item[['$parentId']]), item.id]
            item.level = [...this.getTreeIdList(item[['$parentId']]), item.id].length
          })
          // const setData = (arr, id) => {
          //   arr.map(item => {
             
          //     item.checked = false
          //     this.$forceUpdate()
          //     if (item?.children) {
          //       setData(item.children)
          //     }
          //   })
          // }
          // setData(this.treeData)
          console.log('11111selectChangeData', selectData)
          const data = JSON.parse(JSON.stringify(selectData))
          this.$emit('change', data.reverse())
          
        }

        
				this.judgeFun(this.selectData)
        this.selectData = selectData
        this.$emit('selectChangeData', e)
        
			},
			// 动态获取高度
			getTreeHeight(treeArr, h) {
				// console.log(h)
				// 找到对应的 指定项 children
				let height = 0
				const treeFun = (arr) => {
					arr.map((item, index) => {

						height += h

						if (item?.children && item.scopesDefault) {
							// item.height = height
							// console.log(item)
							treeFun(item.children)

						}
					})

				}
				treeFun(treeArr)
				return Promise.resolve(height)
				// return height
			},
			// 展开/收起
			showlist(index) {
			
				this.treeData[index].scopesDefault = !this.treeData[index].scopesDefault
        // console.log(this.treeData)
				this.setStyles()
				
				this.$forceUpdate()

			}
		}
	}
</script>

<style lang="scss" scoped>
	.treeRadio {
		background: #fff;
		margin-left: 20px;

		.item {
			display: flex;
			padding: 6px 0;
			height: 36px;
			box-sizing: border-box;
      cursor: pointer;

			.left {
				display: flex;
        align-items: center;
        .expanded {
          display: flex;
					align-items: center;
					transition: all 0.4s;
					transform: rotateZ(-90deg) !important;
          margin-right: 5px;
          font-size: 14px;
        }
        .iconfont.down {
          transform: rotateZ(0deg) !important;
        }
        .checkbox {
          display: flex;
          align-items: center;
          justify-content: center;
          position: relative;
          border: 1px solid #dcdfe6;
          border-radius: 2px;
          box-sizing: border-box;
          width: 14px;
          height: 14px;
          background-color: #fff;
          margin-right: 5px;
          .iconfont {
            color: #fff;
            font-size: 12px;
            font-weight: bold;
          }
        }
        .select {
          background-color: #872727;
          border-color: #872727;
        }
			}

			.right {
				display: flex;
				align-items: center;

			


			}

			
		}

		.tree_children {
			// transition: all 0.4s;
			overflow: hidden;
		}
	}
</style>